#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <sys/epoll.h>

int main(int argc, const char *argv[])
{
    // 创建套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    // 绑定本地IP和端口
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_port = htons(9999);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);
    serv.sin_family = AF_INET;
    bind(lfd, (struct sockaddr *)&serv, sizeof(serv));

    // 监听
    listen(lfd, 128);

    // 等待接收连接请求
    struct sockaddr_in client;
    int len = sizeof(client);
    // 创建epoll树的根节点
    int epfd = epoll_create(2000);
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = lfd;
    // 将监听套接字加到epoll 树上
    epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);

    struct epoll_event all[2000];
    while (1)
    {
        // 委托内核进行操作
        int ret = epoll_wait(epfd, all, sizeof(all) / sizeof(all[0]), -1);
        // 如果有新客户端链接
        for (int i = 0; i < ret; ++i)
        {
            int fd = all[i].data.fd;
            if (fd == lfd)
            {
                // 接收新连接请求
                int cfd = accept(fd, (struct sockaddr *)&client, &len);
                if (cfd == -1)
                {
                    printf("客户端链接失败\n");
                    exit(1);
                }
                // 打印客户端信息
                char ip[64];
                printf("client IP: %s, port: %d\n", inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)), ntohs(client.sin_port));

                struct epoll_event temp;
                temp.data.fd = cfd;
                temp.events = EPOLLIN;
                // 将新连接的客户端挂到epoll树上
                epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &temp);
            }
            else
            {
                char buf[1024];
                // 客户端发送过来一些数据
                int len = recv(fd, buf, sizeof(buf), 0);
                if (len == -1)
                {
                    printf("read error\n");
                    exit(1);
                }
                else if (len == 0)
                {
                    printf("客户端断开了链接\n");
                    // 从epoll树上删除
                    epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
                    close(fd);
                }
                else
                {
                    printf("revc %s\n", buf);
                    write(fd, buf, len);
                }
            }
        }

        // 客户端有信息发送过来
    }

    close(lfd);

    return 0;
}
